package com.kania.simpleemail.core;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import android.util.Log;

import com.kania.simpleemail.data.MailData;

public class SMTP implements IMailSender{
	private static SMTP SMTPInstance = new SMTP();
	
	private String sHost;
	private String sID;
	private String sPassword;
	
	private MailData sendMailData;
	
	private Session session;
	
	private final String STRING_SMTP_NAME = "smtp";
	private final String STRING_SMTP_SSL_PORT = "465";
	private final String STRING_SOCKETFACTORY_NAME = "javax.net.ssl.SSLSocketFactory";
	
	private final String sTag = "KANIA_LOG_CORE";

	private SMTP () {
		Log.d(sTag, "create singleton IMAP Instance");
	}
	
	public void setHost (String _host) {
		sHost = _host;
	}
	public void setID (String _id) {
		sID = _id;
	}
	public void setPassword (String _password) {
		sPassword = _password;
	}
	public void setSendMailData (MailData _md) {
		sendMailData = _md;
	}
	public void initSMTP (String _host, String _id, String _password) {
		setHost(_host);
		setID(_id);
		setPassword(_password);
	}
	
	public static SMTP getInstance() {
		return SMTPInstance;
	}
	
	@Override
	public void open() throws MessagingException {
		Properties props = new Properties();
		
		props.put("mail.transport", STRING_SMTP_NAME);
		props.put("mail.smtp.host", sHost); 
		props.put("mail.smtp.port", STRING_SMTP_SSL_PORT);
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.socketFactory.class", STRING_SOCKETFACTORY_NAME);
		props.put("mail.smtp.user", sID);
		props.put("mail.smtp.auth", "true");
		
		MailAutentication auth = new MailAutentication(sID, sPassword);
		Log.d(sTag, "complete get auth of " + sID);
		session = Session.getInstance(props, auth);
		Log.d(sTag, "get Session instance successfully");

	}

	@Override
	public void close() throws MessagingException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void send() throws MessagingException {
		// TODO Auto-generated method stub
		MimeMessage msg = new MimeMessage(session);
		msg.setFrom(new InternetAddress(sendMailData.getFromData()));
		msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sendMailData.getToData()));
		msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(sendMailData.getCCData()));
		msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(sendMailData.getBCCData()));
		msg.setSubject(sendMailData.getMailSubject());
		msg.setText(sendMailData.getContents()); //TODO 해당 부분은 이후 멀티파트로 구성될 수 있도록 한다.
		msg.setSentDate(new Date());
		
		Transport.send(msg);
		Log.d(sTag, "mail send task end");
	}
	
	
	

}
